package com.nit.service.impl;

import com.nit.dto.GoodsDTO;
import com.nit.dto.StockInDTO;
import com.nit.dto.StockOutDTO;
import com.nit.dto.utils.PaginationDTO;
import com.nit.dto.utils.TableRequestDTO;
import com.nit.dto.utils.TableResponseDTO;
import com.nit.entity.GoodsEntity;
import com.nit.entity.StockInEntity;
import com.nit.mapper.StockInMapper;
import com.nit.service.StockInService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class StockInServiceImpl implements StockInService {
    @Resource
    private StockInMapper stockInMapper;

    @Override
    public TableResponseDTO query(TableRequestDTO tableRequestDTO, Long userId) throws Exception {

        Long count = stockInMapper.count4Table(
                tableRequestDTO.getJsonSearch().get("goodsName"),
                tableRequestDTO.getJsonSearch().get("goodsCate"),
                userId
        );
        List<StockInDTO> stockOutDTOS = stockInMapper.list4Table(
                tableRequestDTO.getStart(count),
                tableRequestDTO.getPageSize(),
                tableRequestDTO.getJsonSearch().get("goodsName"),
                tableRequestDTO.getJsonSearch().get("goodsCate"),
                userId
        );
        TableResponseDTO tableResponseDTO = new TableResponseDTO(stockOutDTOS,
                new PaginationDTO(tableRequestDTO.getPageSize(),
                        count, tableRequestDTO.getCurrentPage(),
                        String.valueOf(tableRequestDTO.getSearch())));
        return tableResponseDTO;
    }

//    @Override
//    public Integer getShop(Long userId) throws Exception {
//        return stockInMapper.getShop(userId);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long add(StockInDTO stockInDTO,Long userId) throws Exception {
        stockInDTO.setUserId(userId);
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        StockInEntity stockInEntity = mapperFactory.getMapperFacade().map(stockInDTO, StockInEntity.class);
        stockInEntity.setShopId(stockInMapper.getShop(stockInEntity.getUserId()));
        stockInEntity.setGmtCreate(new Date());
        stockInMapper.add(stockInEntity);
        return stockInEntity.getSiId();
    }
}
